package com.example.aliyun.plus.producer_consumer;
/**
 * Message 用于保存生产消费之间的媒介（类似于数据库）
 */
class Message {
    private String title;

    private String content;

    private boolean flag = true; // true: 允许生产 不允许消费 false： 不允许生产 允许消费
    /**
     * 问题：数据一致，但是会出现重复数据问题
    public synchronized void set(String title, String content) {
        this.title = title;
        this.content = content;
    }

    public synchronized String get(){
        return this.title + " - " + this.content;
    }
     */

    public synchronized void set(String title, String content) {
        if (this.flag == false) { // false： 不允许生产， 即等待
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.title = title;
        this.content = content;
        this.flag = false; // 生产完之后设置flag，唤醒等待线程
        super.notify(); // 唤醒等待的线程
    }

    public synchronized String get(){
        if (this.flag == true) { // true: 不允许消费, 即等待
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try{
            return this.title + " - " + this.content;
        }finally { // 最终消费完之后设置flag，唤醒等待线程
            this.flag = true;
            super.notify();
        }
    }
}

/**
 * 会有数据同步问题
 */
public class ProducerTest {
    public static void main(String[] args) {
        Message msg = new Message();
        new Thread(new Producer(msg)).start();
        new Thread(new Consumer(msg)).start();
    }
}

/**
 * 模拟生产者生产一百个消息
 */
class Producer implements Runnable{
    private Message msg;

    public Producer(Message msg){
        this.msg = msg;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (i % 2 == 0) {
                msg.set("王建", "好帅");
            }else {
                msg.set("李四", "很戳");
            }
        }
    }
}

/**
 * 模拟消费者消费生产者的100 个消息
 */
class Consumer implements Runnable{
    private Message msg;
    public Consumer(Message msg) {
        this.msg = msg;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(msg.get());
        }
    }
}
